package com.lanou.realm;

import com.lanou.entity.User;
import com.lanou.service.PermissionService;
import com.lanou.service.RoleService;
import com.lanou.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * Description: Hello World!
 * author: 何雨轩
 * Create at: 18/7/18 下午8:33
 */
// 继承授权的realm
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    // 获取授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        String username = String.valueOf(principalCollection.getPrimaryPrincipal());

        Set<String> roles = roleService.findByUsername(username);
        Set<String> permissions = permissionService.findByUsername(username);

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    // 获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 用户名
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.findByUsername(username);
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "myRealm");
        } else {
            return null;
        }
    }
}
